package ordersSpu

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"insighttracking/apps/sorting/auth"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/sorting/internal/svc"
	"insighttracking/apps/sorting/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetOrdersSpuListApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetOrdersSpuListApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetOrdersSpuListApiLogic {
	hostname, _ := os.Hostname()
	return &GetOrdersSpuListApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetOrdersSpuListApiLogic) GetOrdersSpuListApi(req *types.GetOrdersSpuReq) (resp []types.GetOrdersSpuResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	fmt.Println(accountInfo)
	// 查询当前企业下全部的订单
	ordersEntities, err := service.OrdersService.GetSendGoodsDateListApi(l.ctx, accountInfo.EnterpriseId, req.StartDate, req.EndDate, req.WarehouseID)
	if err != nil || len(ordersEntities) == 0 {
		return make([]types.GetOrdersSpuResp, 0), nil
	}
	// 获取订单ID
	orderIdList := k.Map(ordersEntities, func(item *model.OrdersEntity, index int) int64 {
		return item.ID
	})

	resp = make([]types.GetOrdersSpuResp, 0)
	totalMap, err := service.OrdersDetailService.GetTotalSpuApi(l.ctx, orderIdList)
	for _, v := range totalMap {
		orderDetailIdList := v.OrderDetailIDs
		var sortingCount = decimal.Zero // 分拣重量:已经分拣的重量
		var completeOrdersCount int     // 分拣进度:完成种类数量
		storeSortingDetail, err := service.StoreSortingDetailService.GetStoreSortingDetailByOrdersDetailIdListApi(l.ctx, orderDetailIdList)
		logx.WithContext(l.ctx).Infof("查询已经分拣的数据:%v", k.MapToString(storeSortingDetail))
		if err == nil && len(storeSortingDetail) > 0 {
			for _, item1 := range storeSortingDetail {
				sortingCount = sortingCount.Add(item1.OutboundCount)
			}
			ordersDetailIDList := k.Map(storeSortingDetail, func(item *model.StoreSortingDetailEntity, index int) int64 {
				return item.OrdersDetailID
			})
			completeOrdersCount = len(k.Distinct(ordersDetailIDList))
		}

		resp = append(resp, types.GetOrdersSpuResp{
			SpuId:               v.SpuID,                     // 商品id
			Name:                v.SpuName,                   // 商品名称
			UnitName:            v.UnitName,                  // 单位,关联到unit表主键id
			TotalCount:          v.Count.StringFixed(2),      // 分拣重量:订单商品总重量
			SortingCount:        sortingCount.StringFixed(2), // 分拣重量:已经分拣的重量
			OrdersCount:         int64(len(v.OrderIDs)),      // 分拣进度:订单种类数量
			CompleteOrdersCount: int64(completeOrdersCount),  // 分拣进度:完成种类数量
		})
	}

	//ordersDetailEntities, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, orderIdList)
	//if err != nil || len(ordersDetailEntities) == 0 {
	//	return make([]types.GetOrdersSpuResp, 0), nil
	//}
	//spuMap := k.ToMap(ordersDetailEntities, func(item *model.OrdersDetailEntity) (int64, *model.OrdersDetailEntity) {
	//	return item.SpuID, item
	//})
	//
	//ordersDetailGroup := k.GroupBy(ordersDetailEntities, func(item *model.OrdersDetailEntity) int64 {
	//	return item.SpuID
	//})
	//for spuId, orderDetailList := range ordersDetailGroup {
	//	spuEntity := spuMap[spuId]
	//	var totalCount = decimal.Zero // 分拣重量:订单商品总重量
	//
	//	var orderDetailIdList = make([]int64, 0)
	//	for _, item := range orderDetailList {
	//		totalCount = totalCount.Add(item.SpuCount)
	//		orderDetailIdList = append(orderDetailIdList, item.ID)
	//	}
	//	logx.WithContext(l.ctx).Infof("当前订单详情:%v", orderDetailIdList)
	//	// 计算已经分拣的重量和种类数量
	//	var sortingCount = decimal.Zero // 分拣重量:已经分拣的重量
	//	var completeOrdersCount int     // 分拣进度:完成种类数量
	//	storeSortingDetail, err := service.StoreSortingDetailService.GetStoreSortingDetailByOrdersDetailIdListApi(l.ctx, orderDetailIdList)
	//	logx.WithContext(l.ctx).Infof("查询已经分拣的数据:%v", k.MapToString(storeSortingDetail))
	//	if err == nil && len(storeSortingDetail) > 0 {
	//		for _, item1 := range storeSortingDetail {
	//			sortingCount = sortingCount.Add(item1.OutboundCount)
	//		}
	//		ordersDetailIDList := k.Map(storeSortingDetail, func(item *model.StoreSortingDetailEntity, index int) int64 {
	//			return item.OrdersDetailID
	//		})
	//		completeOrdersCount = len(k.Distinct(ordersDetailIDList))
	//	}
	//
	//	result = append(result, types.GetOrdersSpuResp{
	//		SpuId:               spuId,                       // 商品id
	//		Name:                spuEntity.SnapshotName,      // 商品名称
	//		UnitName:            spuEntity.SnapshotUnit,      // 单位,关联到unit表主键id
	//		TotalCount:          totalCount.StringFixed(2),   // 分拣重量:订单商品总重量
	//		SortingCount:        sortingCount.StringFixed(2), // 分拣重量:已经分拣的重量
	//		OrdersCount:         int64(len(orderDetailList)), // 分拣进度:订单种类数量
	//		CompleteOrdersCount: int64(completeOrdersCount),  // 分拣进度:完成种类数量
	//	})
	//}
	return
}
